// 将下划线分割的字段名转换为小驼峰分割
export function toCamelCase(obj: any): any {
  if (Array.isArray(obj)) {
    return obj.map(toCamelCase)
  } else if (obj !== null && obj.constructor === Object) {
    return Object.keys(obj).reduce((acc, key) => {
      const camelKey = key.replace(/_([a-z])/g, (_, letter) =>
        letter.toUpperCase()
      )
      acc[camelKey] = toCamelCase(obj[key])
      return acc
    }, {} as any)
  }
  return obj
}

// 将小驼峰分割的字段名转换为下划线分割
export function toSnakeCase(obj: any): any {
  if (Array.isArray(obj)) {
    return obj.map(toSnakeCase)
  } else if (obj !== null && obj !== undefined && obj.constructor === Object) {
    return Object.keys(obj).reduce((acc, key) => {
      const snakeKey = key.replace(/([A-Z])/g, "_$1").toLowerCase()
      acc[snakeKey] = toSnakeCase(obj[key])
      return acc
    }, {} as any)
  }
  return obj
}

// 计算文本宽度的函数，使用 canvas 渲染文本来测量宽度
export function getTextWidth(
  text: any[],
  font: string = "14px Microsoft YaHei"
): number {
  const canvas = document.createElement("canvas")
  const context = canvas.getContext("2d")
  if (context) {
    context.font = font
    return Math.max(...text.map((t) => context.measureText(t).width)) + 60
  }
  return 0
}

/**
 * 通用树形结构构造方法
 * @param data 原始数组
 * @param id 主键字段名，默认 'id'
 * @param parentId 父级字段名，默认 'parentId'
 * @param childrenKey 子节点字段名，默认 'children'
 * @returns 树形结构数组
 */
export function buildTree(
  data: any[],
  id: string = "id",
  parentId: string = "parentId",
  childrenKey: string = "children"
): any[] {
  const map: { [key: string]: any } = {}
  const tree: any[] = []

  data.forEach((item) => {
    map[item[id]] = { ...item, [childrenKey]: [] }
  })

  data.forEach((item) => {
    const parent = map[item[parentId]]
    if (
      parent &&
      item[parentId] !== 0 &&
      item[parentId] !== null &&
      item[parentId] !== undefined
    ) {
      parent[childrenKey].push(map[item[id]])
    } else {
      tree.push(map[item[id]])
    }
  })

  return tree
}
